﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using Lenovo.CFI.BLL;
using Lenovo.CFI.Common.Dic;
using Lenovo.CFI.WebControls;
using Lenovo.CFI.Web.Helper;
using Lenovo.CFI.Common;
using Lenovo.CFI.BLL.Sys;
using Lenovo.CFI.BLL.DicMgr;

namespace Lenovo.CFI.Web.VP
{
    public partial class TopicIdeaStatus : System.Web.UI.UserControl
    {
        TopicBl topicBl = new TopicBl();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (!IsPostBack)
                {
                    int? id = UrlHelper.GetQueryStringID();
                    Topic topic = null;
                    if (id.HasValue)
                    {
                        topic = topicBl.GetTopicByID(id.Value);
                    }
                    if (topic == null) ErrorHelper.RaiseNoValueError();

                    ViewState["topicid"] = topic.ID;

                    MessageHelper.Prepare(this.Page);

                    BindHelper.BindIdeaType(this.DdlReviewType, null, null, null, false);

                    if (topic.Status != TopicStatus.Suggestion && topic.Status != TopicStatus.Execution && topic.Status != TopicStatus.Closed)
                    {
                        ErrorHelper.RaiseError("The specified topic can't be changed!");
                    }

                    ViewState["sort"] = false;

                    this.BindData();
                }
            }
        }


        Dictionary<int, Idea> ideasDic = null;
        private void BindData()
        {
            int topicID = (int)ViewState["topicid"];

            ReviewBl reviewBl = new ReviewBl();
            List<IdeaReview> ideaReviews = reviewBl.GetReview(topicID);
            Dictionary<int, IdeaReview> reviewsDic = new Dictionary<int, IdeaReview>();
            foreach (IdeaReview ideaReview in ideaReviews)
                reviewsDic.Add(ideaReview.ID, ideaReview);

            List<Idea> ideas = new IdeaBl().GetIdeaForReview(topicID);
            ideasDic = new Dictionary<int, Idea>();
            foreach (Idea idea in ideas) ideasDic.Add(idea.ID, idea);

            List<IdeaReviewDetail> details = reviewBl.GetReviewDetail(topicID, (string)ViewState["reviewer"]);
            foreach (IdeaReviewDetail detail in details)
                reviewsDic[detail.ReviewID].Details.Add(detail);

            if ((bool)ViewState["sort"])
            {
                ideaReviews.Sort((x, y) => y.ReviewScore.CompareTo(x.ReviewScore));
            }

            this.GvList.DataSource = ideaReviews;
            this.GvList.DataBind();
        }

        protected void GvList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                // 设置行号
                ((Literal)(e.Row.FindControl("LtrNo"))).Text = String.Format("{0}", e.Row.DataItemIndex + 1);

                IdeaReview review = (IdeaReview)e.Row.DataItem;
                Idea idea = ideasDic[review.IdeaID];

                ((Literal)e.Row.FindControl("LtrTitle")).Text = String.Format(@"<a href=""{0}"" target=""_blank"">{1}</a>",
                    UrlHelper.GenerateUrl("ideadetail", "id", idea.ID.ToString()), idea.Title);
                ((Literal)e.Row.FindControl("LtrOwner")).Text = idea.Owner;
                ((Literal)e.Row.FindControl("LtrType")).Text = IdeaTypeDicMgr.GetByCode(review.ReviewType).Title;
                ((Literal)e.Row.FindControl("LtrValue")).Text = review.ReviewScore.ToString("f2") + (review.Award.HasValue ? "[" + review.Award.Value.ToString() + "]" : "");
                ((Literal)e.Row.FindControl("LtrNextAction")).Text = review.NextActionDescription();
                ((Literal)e.Row.FindControl("LtrIP")).Text = review.NextIPDescription();


                if (review.DcConfirmed == SuggestionStatus.Reject)
                {
                    e.Row.CssClass += " rejected";
                }
            }
        }

        protected void GvList_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "OpenEdit")
            {
                int reviewID = Convert.ToInt32(e.CommandArgument);
                ViewState["ReviewID"] = reviewID;

                ReviewBl reviewBl = new ReviewBl();

                IdeaReview review = reviewBl.GetReviewByID(reviewID);
                Idea idea = new IdeaBl().GetIdeaById(review.IdeaID);


                if (review.DcConfirmed == SuggestionStatus.Reject)
                {
                    this.DdlReviewType.ClearSelection();
                    ListItem item = this.DdlReviewType.Items.FindByValue(review.NextAction);
                    if (item != null) item.Selected = true;

                    this.MpeReviewType.Show();
                }
                else
                {
                    if (idea.Status == IdeaStatus.Closed)
                    {
                        this.OuacExecutor.Enabled = false;
                    }
                    else
                    {
                        this.OuacExecutor.Enabled = true;
                    }

                    this.DdlAward.ClearSelection();
                    if (review.Award.HasValue)
                    {
                        this.DdlAward.Items.FindByValue(review.Award.Value.ToString()).Selected = true;
                    }
                    this.TxtAwardComment.Text = review.AwardComment;

                    this.OuacExecutor.Text = review.ActionExecutor;

                    this.MpeEdit.Show();
                }
            }
        }

        protected void BtnSave_Click(object sender, EventArgs e)
        {
            int reviewID = (int)ViewState["ReviewID"];

            int? award = null;
            if (this.DdlAward.SelectedIndex != 0)
                award = Convert.ToInt32(this.DdlAward.SelectedValue);

            try
            {
                new ReviewBl().Award(reviewID, award, this.TxtAwardComment.Text, this.OuacExecutor.Text);

                MessageHelper.RegShowJSAjax(this.BtnSave, "Success!", this.Page);
            }
            catch (ApplicationException ex)
            {
                MessageHelper.RegShowJSAjax(this.BtnSave, ex.Message, this.Page);
            }
            catch (Exception ex)            // Ajax无法使用默认异常处理程序处理异常
            {
                ErrorHelper.ExceptionHanderForAjax(ex, this.BtnSave, this.Page);
            }

            this.BindData();
        }

        protected void BtnOrder_Click(object sender, EventArgs e)
        {
            ViewState["sort"] = !((bool)ViewState["sort"]);

            this.BindData();
        }

        protected void BtnReviewTypeSave_Click(object sender, EventArgs e)
        {
            int reviewID = (int)ViewState["ReviewID"];

            try
            {
                new ReviewBl().ResetType(reviewID, this.DdlReviewType.SelectedValue);

                MessageHelper.RegShowJSAjax(this.BtnReviewTypeSave, "Success!", this.Page);
            }
            catch (ApplicationException ex)
            {
                MessageHelper.RegShowJSAjax(this.BtnReviewTypeSave, ex.Message, this.Page);
            }
            catch (Exception ex)            // Ajax无法使用默认异常处理程序处理异常
            {
                ErrorHelper.ExceptionHanderForAjax(ex, this.BtnReviewTypeSave, this.Page);
            }

            this.BindData();
        }

    }
}